module.exports = {
  meta: {
    type: "problem",
    docs: {
      description:
        "确保 setInterval 使用 clearInterval 清除。例如 this.timer = setInterval(() => {}, 1000), 需要clearInterval(this.timer);",
    },
    schema: [],
    messages: {
      missingClear: "setInterval is not cleared with clearInterval.",
    },
  },

  create(context) {
    const intervalIds = new Map(); // 存储 setInterval 的变量名或表达式

    return {
      CallExpression(node) {
        const callee = node.callee;

        // 检查 setInterval
        if (callee.type === "Identifier" && callee.name === "setInterval") {
          const parent = node.parent;

          if (
            parent.type === "VariableDeclarator" &&
            parent.id.type === "Identifier"
          ) {
            //let a=setInterval(() => {}, 1000)
            const varName = parent.id.name;
            intervalIds.set(varName, { node, used: false });
          } else if (parent.type === "AssignmentExpression") {
            //this.timer = setInterval(() => {}, 1000)
            const varName = parent.left.property.name;
            intervalIds.set(varName, { node, used: false });
          } else {
            // 未存变量名的情况，如 setInterval(...) 直接使用
            intervalIds.set(null, { node, used: false });
          }
        }

        // 检查 clearInterval
        if (
          callee.type === "Identifier" &&
          callee.name === "clearInterval" &&
          node.arguments.length > 0
        ) {
          const arg = node.arguments[0];
          //clearInterval(a);
          if (arg.type === "Identifier") {
            const id = arg.name;
            if (intervalIds.has(id)) {
              intervalIds.get(id).used = true;
            }
          } else if (arg.type === "MemberExpression") {
            //clearInterval(this.timer);
            const id = arg.property.name;
            if (intervalIds.has(id)) {
              intervalIds.get(id).used = true;
            }
          }
        }
      },

      "Program:exit"() {
        // 报告未被清除的定时器
        for (const [id, record] of intervalIds.entries()) {
          if (!record.used) {
            context.report({
              node: record.node,
              message: `setInterval 未使用 clearInterval 清除，变量名${id}`,
            });
          }
        }
      },
    };
  },
};
